package com.mrx.spring.example.runner;

import com.mrx.commons.http.RestTemplateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author Mr.X
 * @since 2023-11-17 09:32
 **/
@Component
public class RestTemplateRunner {

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private RestTemplateUtils restTemplateUtils;
    private static final String TEST_URL = "https://httpbin.org/post";
    private static final Logger logger = LoggerFactory.getLogger(RestTemplateRunner.class);

    @Async("traceExecutor")
    @EventListener(ApplicationReadyEvent.class)
    public void init() {
        try {
            Map<Object, Object> requestBody = Map.of("data", "aabb");
            ResponseEntity<String> response = restTemplate.postForEntity(TEST_URL, requestBody, String.class);
            logger.debug("response: {}", response.getBody());
            String result = restTemplateUtils.postJson(TEST_URL, requestBody);
            logger.debug("result: {}", result);
        } catch (Exception e) {
            logger.error("出现异常: ", e);
        }
    }

}
